package com.tuxianchao.springbootmail.manager.service.impl;

import com.tuxianchao.springbootmail.manager.service.EmailService;
import javafx.beans.binding.ObjectExpression;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * created by
 *
 * @author tuxianchao
 * @date 2018/5/12 下午2:54
 */
@Service
public class EmailServiceImpl implements EmailService {


    private Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
    /**
     * 邮件发送者
     */
    @Value("${spring.mail.username}")
    private String emailFrom;
    /**
     * javamail
     */
    @Autowired
    private JavaMailSender javaMailSender;
    /**
     * velocity属性配置，主要是模板资源加载路径的问题
     */
    private static Properties properties;

    static {
        properties = new Properties();
        //初始化参数
        //设置velocity资源加载方式为file！！！
        properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "src/main/resources/mail-template");
        properties.setProperty("resource.loader", "file");
        //设置velocity资源加载方式为file时的处理类
        properties.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
    }

    @Override
    public void sendSimpleEmail(String dest, String title, String content) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(emailFrom);
        mailMessage.setTo(dest);
        mailMessage.setSubject(title);
        mailMessage.setText(content);
        //发送邮件
        try {
            javaMailSender.send(mailMessage);
            logger.info("发送邮件成功:[{}],[{}],[{}]", new Object[]{dest, title, content});
        } catch (Exception e) {
            logger.error("邮件发送失败!{}", e);
            e.printStackTrace();
        }
    }

    @Override
    public void sendAttachmentsEmail(String dest, String title, String content, Map<String, File> attachments) {


        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(emailFrom);
            mimeMessageHelper.setTo(dest);
            mimeMessageHelper.setSubject(title);
            mimeMessageHelper.setText(content);
            //添加附件
            Set<String> set = attachments.keySet();
            for (String key : set) {
                mimeMessageHelper.addAttachment(key, attachments.get(key));
            }
            javaMailSender.send(mimeMessage);
            logger.info("发送邮件成功:[{}],[{}],[{}],[{}]", new Object[]{dest, title, content, attachments});
        } catch (MessagingException e) {
            logger.error("邮件发送失败!{}", e);

            e.printStackTrace();
        }
    }

    @Override
    public void sendTemplateEMail(String dest, String title, String templatePath, Map<String, Object> content, Map<String, File> attachments) {

        MimeMessagePreparator preparator = mimeMessage -> {
            // 设置 utf-8防止出现乱码
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8");
            message.setTo(dest);
            message.setFrom(emailFrom);
            message.setSubject(title);

            //渲染模板
            Velocity.init(properties);
            Template template = Velocity.getTemplate(templatePath, "UTF-8");
            VelocityContext velocityContext = new VelocityContext();
            StringWriter writer = new StringWriter();
            Set<String> contentKeys = content.keySet();
            for (String contentKey : contentKeys) {
                velocityContext.put(contentKey, content.get(contentKey));
            }
            template.merge(velocityContext, writer);
            //设置为true，否则发过去的是html标签
            message.setText(writer.toString(), true);
            //添加附件
            if (attachments != null) {
                Set<String> set = attachments.keySet();
                for (String key : set) {
                    message.addAttachment(key, attachments.get(key));
                }
            }

        };
        try {
            javaMailSender.send(preparator);
            logger.info("发送邮件成功:[{}],[{}],[{}],[{}]", new Object[]{dest, title, content, attachments});
            logger.error("使用模板:{}", templatePath);

        } catch (Exception e) {
            logger.error("邮件发送失败!{}", e);
            e.printStackTrace();
        }
    }
}
